package com.llyb.tingshu.album.service.impl;

import com.llyb.tingshu.album.config.MinioConstantProperties;
import com.llyb.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Resource
    private MinioConstantProperties minioConstantProperties;

    @Override
    public String upload(MultipartFile file) {

        // 声明url
        String url = "";
        // 上传
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket " + minioConstantProperties.getBucketName() + " already exists.");
            }

            // fileName
            String fileName = UUID.randomUUID().toString().replaceAll("-","") +
                    file.getOriginalFilename().lastIndexOf(".");
            // Upload known sized input stream.
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            // 获取url
            url = minioConstantProperties.getEndpointUrl()+"/"+
                    minioConstantProperties.getBucketName()+"/"+fileName;
            System.out.println(url);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 返回地址
        return url;
    }
}
